package control;

import java.util.Map;
import java.util.TreeMap;
import java.util.Arrays;
import java.util.List;
import java.io.*;
import java.io.FileInputStream;

import amazon.s3.AWSAuthConnection;
import amazon.s3.QueryStringAuthGenerator;
import amazon.s3.S3Object;

public class AccessClass {

    final String awsAccessKeyId = "AKIAIAV4BNPDOS3NMUJA";
    final String awsSecretAccessKey = "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";
    final String bucketName = "project_vps9";
    final String database = "db";
    AWSAuthConnection conn;
    String users[];

    public AccessClass() {
        conn = new AWSAuthConnection(awsAccessKeyId, awsSecretAccessKey);
    }

    /**
     * Loads the database file "db" from the S3 bucket
     * @return true if the file was found and loaded
     *         false if file not found
     */
    public boolean loadDB() {
        String information = null;
        try {
            information = new String(conn.get(bucketName, database, null).object.data);
        } catch (Exception e) {
            return false;
        }
        users = information.split("\n");
        return true;
    }

    /**
     * Authenticate the user
     * @param uname - Username
     * @param pass - Password
     * @return true on success
     *         false on failure
     */
    public boolean auth(String uname, String pass) {
        String indificators[] = null;

        for (String s : users) {
            indificators = s.split(" ");
            if (indificators[0].equals(uname) && indificators[1].equals(pass)) {
                return true;
            }
            indificators = null;
        }
        return false;
    }

    /**
     * Return a list containing all files of the user
     * @param user - Username
     * @return List
     */
    public List getFiles(String user) {
        List filenames = null;
        try {
            filenames = conn.listBucket(bucketName, user + "/", user + "/", null, null).entries;
        } catch (Exception e) {
            return null;
        }
        return filenames;
    }

    /**
     * Generates a temporary link to a file of user's space  
     * @param filename - Name of the file
     * @return URL address to reach that file
     */
    public String generateLink(String filename) {
        QueryStringAuthGenerator generator =
                new QueryStringAuthGenerator(awsAccessKeyId, awsSecretAccessKey);
        //The generated link will be executable 10 seconds.
        //It is possible to reduce the time, but in case of slow internet connection
        //10 seconds is reasonable time.
        generator.setExpiresIn(10 * 1000);
        return generator.get(bucketName, filename, null);
    }

    /**
     * Delete a selected file from user's space
     * @param filename - Name of the file
     * @return true on success
     *         false of failure
     */
    public boolean deleteFile(String filename) {

        String response = null;
        try {
            response = conn.delete(bucketName, filename, null).connection.getResponseMessage();
        } catch (Exception e) {
            return false;
        }
        return true;

    }

    /**
     * Uploads the zipped file into Amazon S3 bucket
     * @param user - Username
     * @param file - The zipped file
     * @return true on success
     *         false on failure
     */
    public boolean uploadFiled(String user, File file) {

        String result = "";
        String outFilename = file.getName();

        File f2 = file;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(f2);

            byte data[] = new byte[(int) f2.length()];
            fin.read(data);

            S3Object object = new S3Object(data, null);

            Map headers = new TreeMap();
            headers.put("Content-Type", Arrays.asList(new String[]{"application/zip"}));
            headers.put("Cache-Control", Arrays.asList(new String[]{"public"}));

            result = conn.put(bucketName, user + "/" + outFilename, object, headers).connection.getResponseMessage();

        } catch (IOException ioe) {
            System.out.println("Exception while reading the file " + ioe);
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
            } catch (IOException ioe) {
                System.out.println("Exception while reading the file " + ioe);
            }
        }

        if (!f2.canWrite()) {
            throw new IllegalArgumentException("Delete: write protected: "
                    + outFilename);
        }
        if (!f2.delete()) {
            throw new IllegalArgumentException("Delete: deletion failed");
        }

        return (result.equals("OK"));
    }
}
